from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse, HttpResponse
from django.views.decorators.http import require_http_methods
from django.core.paginator import Paginator
from django.db.models import Q
import json
from stocks.models import Strategy, BuySignal, Stock
from stocks.services.strategy_service import StrategyService


@require_http_methods(["GET"])
def strategy_list(request):
    """策略列表页面"""
    strategies = Strategy.objects.all().order_by('-created_at')
    
    # 获取每个策略的统计信息
    strategy_stats = []
    for strategy in strategies:
        stats = StrategyService.get_strategy_performance(strategy.id, days=30)
        strategy_stats.append({
            'strategy': strategy,
            'stats': stats
        })
    
    context = {
        'strategy_stats': strategy_stats,
        'title': '交易策略列表'
    }
    return render(request, 'stocks/strategy_list.html', context)


@require_http_methods(["GET"])
def strategy_detail(request, strategy_id):
    """策略详情页面"""
    strategy = get_object_or_404(Strategy.objects.all(), id=strategy_id)
    
    # 获取策略表现统计
    performance_30d = StrategyService.get_strategy_performance(strategy_id, days=30)
    performance_90d = StrategyService.get_strategy_performance(strategy_id, days=90)
    
    # 获取近期信号
    recent_signals = StrategyService.get_recent_signals(days=30, min_strength=0)
    strategy_signals = [s for s in recent_signals if s.get('strategy_name') == strategy.name]
    
    context = {
        'strategy': strategy,
        'performance_30d': performance_30d,
        'performance_90d': performance_90d,
        'recent_signals': strategy_signals[:20],  # 显示最近20个信号
        'title': f'{strategy.name} - 策略详情'
    }
    return render(request, 'stocks/strategy_detail.html', context)


@require_http_methods(["GET"])
def buy_signals(request):
    """买入信号列表页面"""
    # 获取筛选参数
    symbol = request.GET.get('symbol', '')
    strategy_id = request.GET.get('strategy', '')
    min_strength = request.GET.get('min_strength', '50')
    days = request.GET.get('days', '7')
    
    try:
        min_strength = float(min_strength)
        days = int(days)
    except (ValueError, TypeError):
        min_strength = 50
        days = 7
    
    # 构建查询条件 - 避免跨数据库关联查询
    filters = Q()
    if symbol:
        # 直接使用stock_id字段而不是stock__symbol关联查询
        filters &= Q(stock_id__icontains=symbol)
    if strategy_id:
        filters &= Q(strategy_id=strategy_id)
    
    # 获取信号 - 避免跨数据库关联查询
    signals = BuySignal.objects.filter(filters).filter(
        signal_strength__gte=min_strength
    ).order_by('-signal_date', '-signal_strength')
    
    # 分页
    paginator = Paginator(signals, 50)
    page_number = request.GET.get('page', 1)
    page_obj = paginator.get_page(page_number)
    
    # 获取所有策略用于筛选
    strategies = Strategy.objects.all()
    
    context = {
        'page_obj': page_obj,
        'strategies': strategies,
        'symbol': symbol,
        'strategy_id': strategy_id,
        'min_strength': min_strength,
        'days': days,
        'title': '买入信号列表'
    }
    return render(request, 'stocks/buy_signals.html', context)


@require_http_methods(["GET", "POST"])
def analyze_stock(request, symbol):
    """分析单只股票"""
    stock = get_object_or_404(Stock, symbol=symbol)
    
    # 获取策略ID参数
    strategy_id = request.GET.get('strategy_id')
    
    if request.method == 'POST':
        # 执行分析
        if strategy_id:
            # 执行特定策略分析
            signals = StrategyService.analyze_single_stock_with_strategy(symbol, int(strategy_id))
        else:
            # 执行所有策略分析
            signals = StrategyService.analyze_single_stock(symbol)
        
        # 保存信号
        if signals:
            from stocks.services.signal_generator import StrategyExecutor
            saved_count = StrategyExecutor.save_signals(signals)
            message = f"分析完成，发现 {len(signals)} 个信号，保存 {saved_count} 个"
        else:
            message = "分析完成，未发现买入信号"
        
        context = {
            'stock': stock,
            'signals': signals,
            'message': message,
            'title': f'{stock.symbol} - 策略分析'
        }
        return render(request, 'stocks/analyze_result.html', context)
    
    # GET请求显示分析页面
    context = {
        'stock': stock,
        'strategy_id': strategy_id,
        'title': f'{stock.symbol} - 策略分析'
    }
    return render(request, 'stocks/analyze_stock.html', context)


@require_http_methods(["GET", "POST"])
def analyze_all_stocks(request):
    """批量分析所有股票"""
    if request.method == 'POST':
        batch_size = int(request.POST.get('batch_size', 50))
        
        # 执行批量分析
        results = StrategyService.analyze_all_stocks(batch_size)
        
        return JsonResponse({
            'success': True,
            'results': results
        })
    else:
        # GET请求显示分析页面
        return render(request, 'stocks/analyze_all.html', {
            'title': '批量分析股票'
        })


@require_http_methods(["GET"])
def api_recent_signals(request):
    """API: 获取近期买入信号"""
    days = int(request.GET.get('days', 7))
    min_strength = float(request.GET.get('min_strength', 50))
    limit = int(request.GET.get('limit', 50))
    
    signals = StrategyService.get_recent_signals(days, min_strength)
    
    return JsonResponse({
        'success': True,
        'count': len(signals),
        'signals': signals[:limit]
    })


@require_http_methods(["GET"])
def api_stock_signals(request, symbol):
    """API: 获取某只股票的买入信号"""
    days = int(request.GET.get('days', 30))
    
    signals = StrategyService.get_stock_signals(symbol, days)
    
    return JsonResponse({
        'success': True,
        'symbol': symbol,
        'count': len(signals),
        'signals': signals
    })


@require_http_methods(["GET"])
def api_strategy_performance(request, strategy_id):
    """API: 获取策略表现统计"""
    days = int(request.GET.get('days', 90))
    
    performance = StrategyService.get_strategy_performance(strategy_id, days)
    
    return JsonResponse({
        'success': 'error' not in performance,
        'performance': performance
    })


@require_http_methods(["POST"])
def cleanup_signals(request):
    """清理旧信号"""
    days = int(request.POST.get('days', 365))
    
    deleted_count = StrategyService.cleanup_old_signals(days)
    
    return JsonResponse({
        'success': True,
        'deleted_count': deleted_count,
        'message': f'清理了 {deleted_count} 个{days}天前的旧信号'
    })


@require_http_methods(["GET"])
def strategy_dashboard(request):
    """策略分析仪表板"""
    # 获取近期高强度信号
    strong_signals = StrategyService.get_recent_signals(days=7, min_strength=70)
    
    # 获取策略统计
    strategies = Strategy.objects.filter(is_active=True)
    strategy_performance = []
    
    for strategy in strategies:
        stats = StrategyService.get_strategy_performance(strategy.id, days=30)
        strategy_performance.append({
            'strategy': strategy,
            'stats': stats
        })
    
    # 按信号数量排序
    strategy_performance.sort(key=lambda x: x['stats'].get('total_signals', 0), reverse=True)
    
    context = {
        'strong_signals': strong_signals[:10],  # 显示前10个高强度信号
        'strategy_performance': strategy_performance,
        'title': '策略分析仪表板'
    }
    return render(request, 'stocks/strategy_dashboard.html', context)
